package com.hmdp.lock;

import cn.hutool.core.lang.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁实例
 *
 * @author leizi
 * @date 2024/06/18
 */
@Component
public class SimpleRedisLock implements RedisLock {

    private static final String KEY_PREFIX = "lock:";

    private static final String LOCK_FLAG = UUID.randomUUID().toString(true) + "-";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean tryLock(String lockName, long timeoutSec) {
        // 获取线程标识
        long threadId = Thread.currentThread().getId();
        // 获取锁
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + lockName, LOCK_FLAG + threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock(String lockName) {
        // 获取线程标识
        long threadId = Thread.currentThread().getId();
        String lockKey = KEY_PREFIX + lockName;
        String lockValue = stringRedisTemplate.opsForValue().get(lockKey);
        // 释放自身锁
        if (StringUtils.isNotBlank(lockValue) && lockValue.equals(LOCK_FLAG + threadId)) {
            stringRedisTemplate.delete(lockKey);
        }
    }
}
